/*
 * Copyright 2020 DuJiang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.amorou.rest.crypto.util;

import java.nio.charset.Charset;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * AESUtils
 * 
 * @author DuJiang
 */
public final class AESUtils {

	private static final String ALGORITHM = "CBC";
	private static final String AES_CBC_PKCS7Padding = "AES/CBC/PKCS7Padding";

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * 加密
	 * @param encryptText 需要加密的信息
	 * @param key 密钥字符串
	 * @param iv 向量
	 * @param charset 字符集名称
	 * @return String  加密后Base64编码的字符串
	 */
	public static final String encrypt(final String encryptText, final String key, final String iv, final String charset) {
		try {
			Cipher cipher = Cipher.getInstance(AES_CBC_PKCS7Padding);
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(charset));
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
			return Base64.encodeBase64String(cipher.doFinal(encryptText.getBytes(Charset.forName(charset))));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptText;
	}

	/**
	 * 解密
	 * @param decryptText 需要解密的信息
	 * @param key 密钥字符串
	 * @param iv 向量
	 * @param charset 字符集名称
	 * @return String 解密后的字符串
	 */
	public static final String decrypt(final String decryptText, final String key, final String iv, final String charset) {
		try {
			Cipher cipher = Cipher.getInstance(AES_CBC_PKCS7Padding);
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
			IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(charset));
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
			return new String(cipher.doFinal(Base64.decodeBase64(decryptText)), Charset.forName(charset));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptText;
	}

}